import { cloud } from '@/framework/utils/request'
import store from '@/store'

const tableOpts = {
  configPagination: 1,
  tableData: [],
  toolbarBtn: [],
  // 表格第一列
  firstTableCol: {
    select: true,
    width: 55,
    type: 'selection'
  },
  indexTableCol: {
    label: '序号',
    width: 70
  },
  tableCol: [],
  operator: {
    fixed: 'right',
    align: 'center',
    width: 96,
    operatorBtn: []
  }
}


export function getTablePrivateConfig(item) {
  const isEmpty = (value, mes = '-') => {
    const list = ['', null, undefined]
    if ((list.includes(value) || Array.isArray(value)) && value.length === 0) {
      return mes
    }
  }
  const singleOrMany = (row) => {
    const status = isEmpty(row[item.__vModel__])
    if (status) {
      return status
    }
    let val = ''
    switch (Object.prototype.toString.call(row[item.__vModel__])) {
      case ('[object Array]'): val = row[item.__vModel__]; break
      case ('[object String]'): val = row[item.__vModel__].split(','); break
      default: val = [row[item.__vModel__]]
    }
    const selectVal = (item['__slot__'].options || []).reduce((pre, child) => {
      (val.includes(child.value)) && (pre = pre ? `${pre},${child.label}` : child.label)
      return pre
    }, '')
    return selectVal
  }
  const cascaderLabel = (row) => {
    const status = isEmpty(row[item.__vModel__])
    if (status) {
      return status
    }
    let result = ''; let i = 0
    const findLabel = (arr) => {
      const curRow = arr?.filter((child) => child.value === row[item.__vModel__][i])
      result = result ? `${result},${curRow[0].label}` : curRow[0].label
      i++
      curRow[0].children && findLabel(curRow[0].children)
    }
    findLabel(item.options)
    return result
  }
  const rangeFormatter = (row) => {
    const status = isEmpty(row[item.__vModel__])
    if (status) {
      return status
    }
    return row[item.__vModel__].join(item['range-separator'])
  }
  const numberFormatter = (row) => {
    const status = isEmpty(row[item.__vModel__])
    if (status) {
      return status
    }
    if (row[item.__vModel__] == 0) {
      return '0'
    } else {
      return row[item.__vModel__]
    }
  }
  const obj = {
    cascader: {
      formatter: cascaderLabel
    },
    'dt-upload': {
      type: 'image',
      getImgurl: (row) => {
        const status = isEmpty(row[item.__vModel__])
        if (status) {
          return status
        }
        // isEmpty(row[item.__vModel__])
        const fileId = Array.isArray(row[item.__vModel__]) ? row[item.__vModel__][0].fileId : row[item.__vModel__].split(',')[0]
        return `${process.env.VUE_APP_BASE_API + cloud.file}/sysFileInfo/private/preview?fileId=${fileId}&token=${store.getters.token}`
      },
      previewSrcList: (row) => {
        const status = isEmpty(row[item.__vModel__], [])
        if (status) {
          return status
        }
        // isEmpty(row[item.__vModel__], [])
        const fileIdList = Array.isArray(row[item.__vModel__]) ? row[item.__vModel__] : row[item.__vModel__].split(',')
        return fileIdList.map((child) => {
          const fileId = typeof child === 'object' ? child.fileId : child
          return `${process.env.VUE_APP_BASE_API + cloud.file}/sysFileInfo/private/preview?fileId=${fileId}&token=${store.getters.token}`
        })
      }
    },
    switch: {
      type: 'switch',
      activeValue: item['active-value'],
      inactiveValue: item['inactive-value']
    },
    select: {
      formatter: singleOrMany
    },
    radio: {
      formatter: singleOrMany
    },
    checkbox: {
      formatter: singleOrMany
    },
    'date-range': {
      formatter: rangeFormatter
    },
    'time-range': {
      formatter: rangeFormatter
    },
    'number': {
      formatter: numberFormatter
    }
  }
  return obj
}
export function getTableOptions(json1, json2, handleAdd, handleEdit, handleDelete, handleDetail) {
  const formJson1 = json1 // JSON.parse(json1)
  const formJson2 = json2 // JSON.parse(json2)
  tableOpts.toolbarBtn = []
  tableOpts.tableCol = []
  tableOpts.operator.operatorBtn = []
  // 获取操作列的按钮
  if (formJson2.configButton && formJson2.configButton.indexOf('编辑') !== -1) {
    tableOpts.operator.width = 156
    tableOpts.operator.operatorBtn.push({
      text: '编辑',
      size: 'small',
      click: (row, col, cellValue) => { return handleEdit(row) }
    })
  }
  tableOpts.operator.operatorBtn.push({
    text: '详情',
    size: 'small',
    click: (row, col, cellValue) => { return handleDetail(row) }
  })
  // 获取tableOpts.toolbarBtn
  // tableOpts.toolbarBtn = JSON.parse(formJson2.configButton)?.map(item => {
  if (formJson2.configButton) {
    formJson2.configButton.forEach((item) => {
      if (item === '新增') {
        tableOpts.toolbarBtn.push({
          label: '新增',
          type: 'primary',
          // permission: ['INTERFACEPERMISSION_ADD_BUTTON'],
          click: () => {
            handleAdd()
          }

        })
      } else if (item === '批量删除') {
        tableOpts.toolbarBtn.push({
          label: '批量删除',
          click: () => {
            handleDelete()
          }
        })
      } else {
        return false
      }
    })
  }

  // 是否分页
  tableOpts.configPagination = json2.configPagination
  // 获取 tableOpts.tableCol
  const modelListKeys = (formJson2.configColumn || []).map((item) => {
    return item // 要展示的table列
  })
  const searchListKeys = (formJson2.configSearch || []).map((item) => {
    return item // 要展示的table的搜索条件
  })
  // tableOpts.tableCol = []
  dealTableOptions(formJson1.fields, modelListKeys, searchListKeys)
  return tableOpts
}
function dealTableOptions(arr, modelListKeys, searchListKeys) {
  (arr || []).map((item) => {
    if (item.__config__.layout === 'rowFormItem') {
      dealTableOptions(item.__config__.children, modelListKeys, searchListKeys)
    } else {
      const obj = getTablePrivateConfig(item)
      if (modelListKeys?.includes(item.__vModel__)) {
        const clomeOps = {}
        if (item.__config__.tableColumnType === 'select' || item.__config__.tableColumnType === 'radio' || item.__config__.tableColumnType === 'checkbox') {
          clomeOps.options = item.__slot__.options
        } else if (item.__config__.tableColumnType === 'cascader') {
          clomeOps.options = item.options
        }
        const resultRow = {
          prop: item.__vModel__,
          label: item.__config__.tableColumnType === 'dt-upload' ? `${item.__config__.label}（只展示首图）` : item.__config__.label,
          modelType: item.modelType,
          maxlength: item.maxlength, // 默认30 供搜索条件使用
          search: searchListKeys?.includes(item.__vModel__),
          type: item.__config__.tableColumnType,
          show: true,

          showOverflowTooltip: item.__config__.tableColumnType === 'textarea' || item.__config__.tableColumnType === 'input',
          ...clomeOps

        }
        tableOpts.tableCol.push(obj[item.__config__.tableColumnType] ? { ...resultRow, ...obj[item.__config__.tableColumnType] } : resultRow)
      }

      // if (modelListKeys.includes(item.__vModel__)) {
      //   tableOpts.tableCol.push({
      //     prop: item.__vModel__,
      //     label: item.__config__.label,
      //     maxlength: item.maxlength, // 默认30 供搜索条件使用
      //     // readonly: item.readonly,
      //     // disabled: item.disabled,
      //     // labelWidth: item.__config__.labelWidth,
      //     search: searchListKeys.includes(item.__vModel__),
      //     type: item.__config__.tableColumnType
      //   })
      // }
    }
    return null
  })
}
